package com.ay.controller;

import com.ay.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/login")
public class StudentController {

    @RequestMapping("/login" )
    public String login(){
        return "login";
    }



    @RequestMapping("/addstudent")
  //  @ResponseBody             //@ModelAttribute("s") @Validated Student student  起别名
    public String addStudent(HttpServletRequest req,@Validated Student student, BindingResult result) {



/*这里万万不能用 1if (result != null) 回显后再次提交 result不为null但是也没有错误 就会导致无服务提交到hello.jsp的页面*/
      //  if (result != null)

        if (result.hasErrors())  {
            //校验未通过，获取所有的异常信息并展示出来
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError allError : allErrors) {

                System.out.println(allError.getObjectName()+":"+allError.getDefaultMessage());
                System.out.println(allError.getCode());
                req.setAttribute("warn", allError.getDefaultMessage());

            }

            return "backshow";  //数据回显
        }
        return "hello";
    }


    @RequestMapping("/my" )
    public String login2(){
        return "my";
    }




}